package com.javaweb.model.upload;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.javaweb.model.User;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/20 18:53
 */
@Slf4j
public class UserUploadListener implements ReadListener<UserUpload> {
    private static final int BATCH_COUNT = 5 ;
    private List<UserUpload> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(UserUpload user, AnalysisContext analysisContext) {
        log.info("read a data:{}", user);
        cachedDataList.add(user);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成") ;
    }
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        log.info("存储数据库成功");
    }
}
